<template>
  <div class="nowrap" style="width:100%">
    <!-- 顶部按钮 -->
    <el-row type="flex" justify="space-between" align="middle">
      <el-col>
        <el-select
          id="cj_select"
          v-model="selectedScene"
          placeholder="请选择现有场景"
          style="margin-left:20px;margin-right:20px"
        >
          <el-option
            v-for="item in scenetable"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @click.native="getSslListBySceneID(item.value)"

          />
        </el-select>
        <el-button
          type="primary"
          @click="showForm"
          plain
          style="background-color: blue; color: white"
          >新建场景</el-button
        >

        <el-button type="primary" @click="viewSceneBasicInfo"
          >场景基本情况和双方参战条件对比</el-button
        >

        <el-button
          type="primary"
          @click="open"
          plain
          style="background-color: orange; color: black"
        >
          本体建模
        </el-button>
        <el-button type="danger" @click="viewSceneAssessment"
          >查看场景评估结果</el-button
        >

        <el-button type="primary" @click="showImage" v-show="showImageFlag">查看场景示意图</el-button>


        <!--        <el-button type="primary" @click="compareAnalysis">对比分析</el-button>-->
      </el-col>
    </el-row>

    <!-- 中间部分 -->
    <el-row>
      <!-- 左侧 -->
      <el-col :span="0">
        <!-- 场景描述 -->
        <el-card>
          <div
            style="height: 200px; background-color: #b3d7ff"
            class="description"
          >
            <h3>场景描述</h3>
            <!-- 场景描述内容 -->
            <p ref="sceneDescription">
              xxx
            </p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="0">
        <!-- 对比情况 -->
        <el-card>
          <div
            style="height: 200px; background-color: #b3d7ff"
            class="comparison"
          >
            <h3>参战条件</h3>
            <!-- 对比情况内容 -->
          </div>
        </el-card>
      </el-col>
      <el-col :span="0">
        <!-- 杀伤链列表 -->
        <el-card>
          <div style="height: 200px; background-color: #b3d7ff;overflow:auto" class="list">
            <h3>杀伤链列表</h3>

            <!-- 列表内容 -->
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div style="width:100%;"> 
      <!-- 左侧 -->
      <span style="min-width:220px;display: inline-block;" >
        <!-- 武器的三个层次 -->
        <el-card>
          <div
            style="height: 800px; width: 220px;overflow:auto;"
            class="description bc infinite-list-wrapper"
            
          >
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <h3 style="margin-left:10px">杀伤链列表</h3>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: flex-end;
                "
              >
                <button
                  style="width: 100px; height: 40px"
                  @click="selectSsl(0, null)"
                >
                  展示全部
                </button>
              </div>
            </div>
            <el-table :data="sslTrueList" style="width: 100%" border v-loading="loading">
              <el-table-column label="杀伤链">
                <template slot-scope="scope">
                  <!-- 使用 Tooltip 组件包裹 router-link，设置 content 属性为提示信息 -->
                  <!-- <el-tooltip content="点击查看杀伤链详情"> -->
                    <!-- <router-link
                      :to="'/analyse/show?id=' + scope.row"
                      style="color: blue"
                    > -->
                      杀伤链-{{ scope.row }}
                    <!-- </router-link> -->
                  <!-- </el-tooltip> -->
                </template>
              </el-table-column>
              <el-table-column label="选择" prop="selected">
                <template slot-scope="scope">
                  <el-button type="text" @click="selectSsl(scope.row)"
                    >选择</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </span>
      <span style="min-width:660px;display: inline-block;">
        <el-card>
          <div
            style="height: 800px;min-width: 650px;"
            class="comparison bc"
          >
            <h2 style="margin-top:10px;text-align:center">杀伤网</h2>
            <index2 :fromParData="parentData" ref="index2"></index2>
          </div>
        </el-card>
      </span>
      <span style="min-width:750px;display: inline-block;">
        <!-- 评估对比结果 -->
        <el-card>
          <div
            style="height: 800px;"
            class="list bc"
          >
            <h2 style="margin-top:10px;text-align:center">杀伤链-{{this.currentSsl}}</h2>
            <index :fromActivityData="parentActivity" ref="index"></index>
          </div>
        </el-card>
      </span>
    </div>

    <!-- 新建场景的对话框 -->
    <el-dialog
      title="新建场景"
      :visible="formDialogVisible"
      @close="closeFormDialog"
    >
      <!-- 这里放置表单的内容 -->
      <!-- 表单内容 -->
      <el-form ref="form" :model="formData" label-width="80px">
        <el-form-item label="场景名称">
          <el-input
            v-model="formData.eventName"
            placeholder="请输入场景名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="场景位置">
          <el-input
            v-model="formData.eventLocation"
            placeholder="请输入场景位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="作战任务">
          <el-input
            v-model="formData.militaryTask"
            placeholder="请输入作战任务"
          ></el-input>
        </el-form-item>
        <el-form-item label="场景时间">
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-date-picker
                  v-model="formData.startTime"
                  type="datetime"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-date-picker
                  v-model="formData.endTime"
                  type="datetime"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="我方装备">
          <el-button type="primary" @click="showEquipmentDialog()">添加我方装备</el-button>
        </el-form-item>
        <el-form-item label="敌方目标">
          <div>
            <span>
              <el-tag>X坐标</el-tag>
              <el-input v-model="formData.target.x" class="position-input" size="small"></el-input>
            </span>
            <span>
              <el-tag>Y坐标</el-tag>
              <el-input v-model="formData.target.y"  class="position-input" size="small"></el-input>
            </span>
            <span>
              <el-tag>Z坐标</el-tag>
              <el-input v-model="formData.target.z"  class="position-input" size="small"></el-input>
            </span>
            <span>
              <el-tag>机动加速度/g</el-tag>
              <el-input v-model="formData.target.a"  class="position-input" size="small"></el-input>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="推理规则">
          <el-row>
            <el-col :span="12">
              <el-checkbox v-model="formData.precisionChecked">准确度不低于</el-checkbox>
              <el-input v-model="formData.precision" size="mini" style="width:100px"></el-input>
            </el-col>
            <el-col :span="12">
              <el-checkbox v-model="formData.accuracyChecked">精度不低于</el-checkbox>
              <el-input v-model="formData.accuracy" size="mini" style="width:100px"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="描述信息">
          <el-input
            type="textarea"
            v-model="formData.description"
            placeholder="请输入描述信息"
          ></el-input>
        </el-form-item>
        <el-form-item label="添加图片">
          <!-- 上传图片的后端接口 -->
          <el-upload
            style="margin-left: 40px"
            ref="upload"
            class="upload-demo"
            :data="{sceneName : this.uploadSceneName}"
            :multiple="false"
            :action="imageUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList">
            <img v-if="imageUrlFlag" :src="localImageUrl" class="avatar">
            <i v-else class="avatar-uploader-icon">点击此处上传场景示意图</i>
          </el-upload>
        </el-form-item>

      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFormDialog">取消</el-button>
        <el-button type="primary" @click="saveForm">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="添加我方装备" :visible.sync="equipmentDialogVisible">
      <!-- 选择预警机 -->
      <el-checkbox v-model="checkedChooseAWACS" style="margin-right:20px"></el-checkbox>
      <el-select v-model="AWACS.name" placeholder="请选择预警机/舰船" style="margin-right:20px">
        <el-option
          v-for="item in AWACSList"
          :key="item.name"
          :label="item.name"
          :value="item.name">
        </el-option>
      </el-select>
      <span>
        <el-tag>X坐标</el-tag>
        <el-input v-model="AWACS.x" class="position-input" size="small"></el-input>
      </span>
      <span>
        <el-tag>Y坐标</el-tag>
        <el-input v-model="AWACS.y"  class="position-input" size="small"></el-input>
      </span>
      <span>
        <el-tag>Z坐标</el-tag>
        <el-input v-model="AWACS.z"  class="position-input" size="small"></el-input>
      </span>
      <span>
        <el-tag>准确度</el-tag>
        <el-input v-model="AWACS.accuracy"  class="position-input" size="small"></el-input>
      </span>
      <el-button type="primary" @click="showDeviationDialog('预警机')" style="display:inline-block">添加误差信息</el-button>
      <el-tooltip class="item" effect="dark" :content="tip" placement="right-start">
        <i class="el-icon-question"></i>
      </el-tooltip>
      
      <div style="width:100px;margin:left;margin-top: 5px;">
        <el-button type="primary" @click="showFormationDialog()" style="display:inline-block;">添加编队</el-button>
      </div>
      
      <!-- 展示编队列表 -->
      <el-table
        :data="formData.formationList"
        style="margin:20px auto ;"
        :border=true
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{'text-align':'center'}">
        <el-table-column
          prop="name"
          label="编队名称"
        >
        </el-table-column>
        <el-table-column
          prop="count"
          label="编队装备总数">
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button @click="deleteFormation(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEquipmentDialog">取消</el-button>
        <el-button type="primary" @click="confirmEquipmentSelection"
          >确认</el-button
        >
      </span>
      <!-- 添加编队 -->
      <!-- 装备列表 -->
    </el-dialog>

    <el-dialog title="编队信息" :visible.sync="formationDialogVisible"
      @close="closeFormationDialog">

      <el-form ref="formationForm" :model="selectedFormation" >
        <el-form-item label="编队名称">
          <el-input v-model="selectedFormation.name" size="medium" placeholder="请输入编队名称" style="width:30%"></el-input>
        </el-form-item>
      
        <!-- 这里选择除了预警机之外的装备 -->
        <el-form-item label="添加装备">
          
          <!-- 装备名字 -->
          <el-select v-model="selectedEquipment.type" placeholder="请选择装备" style="margin-right:20px;">
            <el-option
              v-for="item in NOAWACSList"
              :key="item.name"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>

          <!-- 坐标输入 -->
          <span>
            <el-tag>X坐标</el-tag>
            <el-input v-model="selectedEquipment.x" class="position-input" size="small"></el-input>
          </span>
          <span>
            <el-tag>Y坐标</el-tag>
            <el-input v-model="selectedEquipment.y"  class="position-input" size="small"></el-input>
          </span>
          <span>
            <el-tag>Z坐标</el-tag>
            <el-input v-model="selectedEquipment.z"  class="position-input" size="small"></el-input>
          </span>

          <!-- 装备载量 -->
          <span>
            <el-tag>载弹量</el-tag>
            <el-input-number v-model="selectedEquipment.weapons" :min="0" :max="20" label="请选择装备载弹量" controls-position="right" size="small"></el-input-number>
          </span>
          <!-- 按钮 -->
          <span style="margin-left:20px;">
            <el-tag>准确度</el-tag>
            <el-input v-model="selectedEquipment.accuracy"  class="position-input" size="small"></el-input>
          </span>
          

          <div style="width:250px;margin-top: 10px;display: block;">
            <el-button type="primary" @click="showDeviationDialog('编队装备')" style="display:inline-block">添加误差信息</el-button>
            <el-tooltip class="item" effect="dark" :content="tip" placement="right-start">
              <i class="el-icon-question"></i>
            </el-tooltip>
            <el-button type="primary" @click="addEquipment" style="margin-left: 20px;">添加装备</el-button>
          </div>
          
        </el-form-item>

        <el-table
          :data="formationEquipmentList"
          style="margin:20px auto ;"
          :border=true
          :cell-style="{'text-align':'center'}"
          :header-cell-style="{'text-align':'center'}">
          <el-table-column
            prop="type"
            label="装备名称"
          >
          </el-table-column>
          <el-table-column
            prop="x"
            label="x坐标">
          </el-table-column>
          <el-table-column
            prop="y"
            label="y坐标">
          </el-table-column>
          <el-table-column
            prop="z"
            label="z坐标">
          </el-table-column>
          <el-table-column
            prop="weapons"
            label="载弹量">
          </el-table-column>
          <el-table-column
            prop="accuracy"
            label="准确度">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button @click="deleteEquipment(scope.row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <!-- 确认和取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeFormationDialog">取消</el-button>
        <el-button type="primary" @click="confirmFromationSelection"
          >确认</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="场景基本情况"
      :visible.sync="basicInfoDialogVisible"
      @close="closeBasicInfoDialog"
    >
      <!-- 在这里添加表格的内容 -->
      <el-table :data="tableData" style="width: 100%">
        <!-- 表格的列定义 -->
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="value" label="内容"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="添加误差信息" :visible.sync="deviationDialogVisible">
      <!-- 装备列表 -->
      <el-form ref="equipmentForm" label-width="0">
        <el-row
          v-for="(rule, index) in ruleList"
          :key="index"
          class="equipment-row"
        >
          <!-- 复选框 -->
          <el-col :span="4">
            <el-form-item>
              <el-checkbox
                v-model="rule.checked"
                class="equipment-checkbox"
              ></el-checkbox>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item> 误差{{ index + 1 }} </el-form-item>
          </el-col>

          <!-- 装备名称 -->
          <el-col :span="8">
            <el-form-item>
              <el-input
                v-model="rule.name"
                placeholder="输入误差名"
                class="equipment-quantity"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <!-- 装备名称 -->
          <el-col :span="8">
            <el-form-item>
              <el-input
                v-model="rule.value"
                placeholder="输入误差值"
                class="equipment-quantity"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 确认和取消按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDomain">新增误差</el-button>
        <el-button @click="removeDomain">删除误差</el-button>
        <el-button @click="closeRuleDialog">取消</el-button>
        <el-button type="primary" @click="confirmRuleSelection">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog id="imageDialog" :visible.sync = "imageVisible"  fullscreen:true center>
      <img id="imageDisplay" alt="无场景示意图">
    </el-dialog>
  </div>
</template>

<script>
import * as d3 from "d3";
import { downloadEquipmentname, downloadImage, getSceneInfoBySceneID, openProtege } from '@/api/ssl'
import { creatSslscene } from "@/api/ssl";
import index from "@/views/nested/activity/index.vue";
import index2 from "@/views/nested/stage5/index.vue";
import service from '@/utils/request'

import {
  getList,
  getChainInfo,
  getSslListBySceneID,
  getSceneList,
  getLine,
  getActivity,
} from "@/api/ssl";

export default {
  components: {
    index,
    index2,
  },
  mounted() {
    console.log("mounted")
    this.$nextTick(() => {});
    this.highlightNumbers();
    this.drawWeaponLevels();
    downloadEquipmentname().then((response) => {
      console.log("所有装备")
      console.log(response.data)
      this.AWACSList=[]
      this.NOAWACSList=[]
      this.mannedList=[]
      this.unmannedGunnerList=[]
      this.unmannedScountList=[]
      this.weaponList=[]
      response.data.forEach(item=>{
        if(item.category=="预警机"){
          this.AWACSList.push(item)
        }else if(item.category=="舰船"){
          this.AWACSList.push(item)
        }else if(item.category=="有人机"){
          this.mannedList.push(item)
          this.NOAWACSList.push(item)
        }else if(item.category=="侦察无人机"){
          this.unmannedScountList.push(item)
          this.NOAWACSList.push(item)
        }else if(item.category=="射手无人机"){
          this.unmannedGunnerList.push(item)
          this.NOAWACSList.push(item)
        }else if(item.category=="导弹"){
          this.weaponList.push(item)
          this.NOAWACSList.push(item)
        }else{
          this.weaponList.push(item)
          this.NOAWACSList.push(item)
        }
      })
      this.NOAWACSList = this.NOAWACSList.map((item)=>({
        name: item.name,
        quantity: 0,
        category: item.category,
        weapons:0,
        x:0,
        y:0,
        z:0
      }))
      this.equipmentList = response.data.map((item) => ({
        name: item.name,
        quantity: 0,
        category: item.category
      }));
    });
    this.getScene();
    this.getssl();
    this.imageUrl=service.url+"/api/upload"
    //console.log(this.imageUrl)
    
  },
  data() {
    return {
      url: "D:\\014\\sslTool\\src\\icons\\svg\\add.png",
      srcList: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
      ],
      imageVisible:false,
      downloadImageUrl:"",
      imageUrlFlag:false,
      fileList:[],
      localImageUrl:'',
      baseURL:'',
      imageUrl: '',
      parentData: {}, // 父组件中的数据
      parentActivity:{},
      showDialog: false,
      routerReload: true,
      formDialogVisible: false,
      basicInfoDialogVisible: false, // 控制场景基本情况对话框的显示与隐藏
      formationDialogVisible:false,//新建编队的对话框
      loading:false,
      imgSrc: "",
      uploadSceneName:"",//上传场景名称
      tableData: [
        // 表格数据
        {
          name: "基本情况",
          value:
            "xxx",
        },
        { name: "场景名称", value: "跨域协同空对空作战" },
        { name: "场景位置", value: "xxx" },
        { name: "作战任务", value: "xxx" },
        { name: "场景时间", value: "xxx" },
        // { name: "我方装备", value: "" },
        // { name: "敌方装备", value: "" },
        // ...（其他表格数据）
      ],
      formationEquipmentList:[],
      selectedFormation:{
        name:'',
        count:'',
        equipmentList:[]
      },
      selectedEquipment:{
        name:"",
        type:'',
        category:'',
        x:0,
        y:0,
        z:0,
        weapons:0,
        leader:false,
        accuracy:0,
        deviationList:[
        ]
      },
      formData: {
        eventName: "",
        eventLocation: "",
        militaryTask: "",
        startTime: "",
        endTime: "",
        AWACS:{},
        formationList:[],
        target: {
          x: 0,
          y: 0,
          z: 0,
          a: 0,
        },
        description: "",
        ruleList: [],
        precisionChecked:false,
        precision:0.0,
        accuracyChecked:false,
        accuracy:0.0,
      },
      equipmentDialogVisible: false,
      equipmentList: [
      ],
      checkedChooseAWACS:false,
      NOAWACSList:[],
      AWACS:{
        name:"",
        x:0,
        y:0,
        z:0,
        accuracy:0,
        deviationList:[
        {
            name:"t1误差",
            value:0
          }
        ]
      },
      AWACSList:[],
      mannedList:[],
      unmannedScountList:[],
      unmannedGunnerList:[],
      weaponList:[],
      quantityOptions: [0, 1, 2, 3, 4, 5], // 下拉框中的数量选项
      sslList: [], //  Ssl 对象数组在这里
      sslTrueList: [],
      selectedScene: null, //现有场景选择
      scenetable: [{ value: "选项1", label: "战场场景1" }],
      currentSsl:undefined,
      tableRow: null,
      deviationDialogVisible: false,
      RuleequipmentList: [],
      ruleList: [{ name: "", value: "", checked: false }],
      showImageFlag: false,
      deviaEquipment: '',
      tip:"点此添加自定义误差"
    };
  },

  computed: {
    selectedKillChain() {
      return this.$store.getters.getSelectedKillChain;
    },
  },

  methods: {
    check021(value){
      value=Number(value)
      //console.log(typeof(value))
      if(typeof(value)=="number"&&value>=0&&value<=1){
        return true
      }else{
        return false
      }
    },
    downloadImage(){
      downloadImage(this.selectedScene).then((response)=>{
        const imageInfoBase64 = response.data.fileData
        this.imgSrc = imageInfoBase64
        // const byteNumbers = new Array(imageInfoBase64.length);
        // for (let i = 0; i < imageInfoBase64.length; i++) {
        //   byteNumbers[i] = imageInfoBase64.charCodeAt(i);
        // }
        // const byteArray = new Uint8Array(byteNumbers);
        // const blob = new Blob([byteArray], { type: 'image/png' });
        //
        // // 创建Blob URL并显示在<img>元素中
        // const blobUrl = URL.createObjectURL(blob);
        // this.imgSrc = blobUrl
        // console.log(blobUrl)
        // document.getElementById("imageDisplay").imgSrc = blobUrl;
      })
    },
    showImage(){
      // console.log(this.imgSrc)
      this.imageVisible = true
      this.$nextTick(function () {
        // this.$refs.message.success('我来的刚刚好吧')
        document.getElementById("imageDisplay").src = "data:image/png;base64,"+this.imgSrc;
      })
      // document.getElementById("imageDisplay").src = "https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA1lmdjT.img?w=731&h=484&m=6&x=275&y=77&s=116&d=116";
      // document.getElementById("imageDisplay").
    },
    confirmImageShow(){
      this.imageVisible = false
    },
    handleFileChange(file, fileList) {
      console.log("fileList")
      console.log(fileList)
      if (fileList.length > 0) {
        this.fileList = [];
        this.fileList.push(fileList[fileList.length-1]);
        this.localImageUrl = URL.createObjectURL(fileList[fileList.length-1].raw);
        this.imageUrlFlag=true
      } else {
        this.localImageUrl = ''; // 清空本地图片URL
        this.imageUrlFlag=false
      }
    },
    upload(){
      //手动上传
      this.$refs.upload.submit();
    },
    //深拷贝
    deepClone(obj, newObj) {
      var newObj = newObj || {};
      for (let key in obj) {
          if (typeof obj[key] == 'object') {
              let isArray = Array.isArray(obj[key]);//判断是否数组
              newObj[key] = (isArray == true ? [] : {})
              this.deepClone(obj[key], newObj[key]);
          } else {
              newObj[key] = obj[key]
          }
      }
      return newObj;
    },
    //添加装备到编队
    addEquipment(){
      if(this.selectedEquipment.type==""){
        this.$message({
          message:"请先选择装备",
          type:"error"
        })
        return
      }
      if(!this.check021(this.selectedEquipment.accuracy)){
        this.$message({
          message:"准确度值和误差值只能为0到1的数值",
          type:"error"
        })
        return
      }
      this.equipmentList.forEach(e=>{
        if(e.name==this.selectedEquipment.type){
          this.selectedEquipment.category=e.category
          this.selectedEquipment.name=e.name+"-"+(this.formationEquipmentList.length+1)
        }
      })
      let flag=true
      //导弹只有一个
      if(this.selectedEquipment.category=="导弹"){
        this.formationEquipmentList.forEach(e=>{
          if(e.type==this.selectedEquipment.type){
            flag=false
          }
        })
      }
      let equipment=this.deepClone(this.selectedEquipment,{})
      if(flag){
        this.formationEquipmentList.push(equipment)
      }
      
    },
    deleteEquipment(row){
      this.formationEquipmentList.forEach((equipment,i)=>{
        if(equipment.name==row.name){
          this.formationEquipmentList.splice(i,1)
        }
      })
    },
    //打开误差创建对话框
    showDeviationDialog(str){
      this.deviationDialogVisible=true
      if(str=="预警机"){
        //将误差绑定到预警机上
        this.deviaEquipment=this.AWACS
      }else{
        //绑定到指定装备上
        this.deviaEquipment=this.selectedEquipment
      }
    },
    //关闭编队创建对话框
    closeFormationDialog(){
      this.selectedFormation={
        name:'',
        count:'',
        equipmentList:[]
      }
      this.formationDialogVisible=false
      this.formationEquipmentList=[]
      this.selectedEquipment={
        name:"",
        type:'',
        category:'',
        x:0,
        y:0,
        z:0,
        weapons:0,
        leader:false
      }
    },
    //确认编队创建
    confirmFromationSelection(){
      console.log("编队创建")
      if(this.selectedFormation.name==""){
        this.$message({
          message:"请输入编队名称",
          type:"error"
        })
        return
      }
      if(this.formationEquipmentList.length==0){
        this.$message({
          message:"请添加至少一个装备",
          type:"error"
        })
        return
      }
      //检查长机属性
      for (let index = 0; index < this.formationEquipmentList.length; index++) {
        const e= this.formationEquipmentList[index];
        if(e.category=="有人机"){
          e.leader=true
          break
        }
      }
      //复制编队信息
      let formation={
        name:this.selectedFormation.name,
        equipmentList:this.deepClone(this.formationEquipmentList,{}),
        count:this.formationEquipmentList.length
      }
      this.formationEquipmentList=[]
      this.formData.formationList.push(formation)
      console.log(this.formData.formationList)
      this.closeFormationDialog()
    },
    //删除表中指定编队
    deleteFormation(row){
      this.formData.formationList.forEach((formation,i)=>{
        if(formation.name==row.name){
          this.formData.formationList.splice(i,1)
        }
      })
    },
    showFormationDialog(){
       this.formationDialogVisible =true
    },
    handleAvatarSuccess(res, file) {
      // 将图片信息保存到formData对象中
      this.formData.image = res.data; // 可以根据需要保存其他图片相关的信息
      console.log("res")
      console.log(res)
      // this.localImageUrl = URL.createObjectURL(file.raw);
      //console.log(res.data);
    },
    beforeAvatarUpload(file) {
    },
    addIdToRows() {
      // console.log("addIdToRows12312312312");
      // console.log(this.sslList);
      const tableRows = document.getElementsByClassName("el-table__row");
      // console.log("addIdToRows12312312312");
      // console.log(tableRows);
      // 遍历每一行，为其添加 ID
      console.log("addIdToRows");
      console.log(this.sslList)
      tableRows.forEach((row, index) => {
        row.setAttribute("id", `row-${this.sslList[index].id}`);
      });
    },
    open() {
      this.showDialog = true;
      // console.log('_____________________________');
      // console.log(this.showDialog);
      // console.log('_____________________________');
      openProtege()
      // fetch('http://localhost:3000/openProtege')
      //   .then(response => response.text())
      //   .then(data => {
      //     console.log(data);

      //   })
      //   .catch(error => console.error('错误:', error));
        /*this.showDialog = false;*/
    },
    handleDialogClose() {
      this.showDialog = false;
    },
    addDomain() {
      this.ruleList.push({
        name: "",
        value: "",
        checked: false,
      });
    },
    removeDomain() {
      this.ruleList = this.ruleList.filter((rule) => rule.checked !== true);
    },
    selectItem(row) {
      // row.selected = !row.selected; // 切换选择状态
      // 将选择的信息传递到三层图中的逻辑
      // 可以使用 row.selected 来判断当前行是否被选择
      this.$store.dispatch("selectKillChain", item);
      // 其他逻辑
    },

    // loginToProtege() {
    //   const protegeURL = "http://162.14.69.245:8083/";
    //   const protegeLoginURL = `${protegeURL}#login/`;
    //   const username = "admin";
    //   const password = "418protege418";

    //   // 打开 Protege 登录页面
    //   const loginWindow = window.open(protegeLoginURL, "_blank");

    //   // 等待一段时间后自动填写用户名和密码
    //   setTimeout(() => {
    //     if (loginWindow) {
    //       loginWindow.postMessage(
    //         { action: "setUsername", value: username },
    //         protegeURL
    //       );
    //       loginWindow.postMessage(
    //         { action: "setPassword", value: password },
    //         protegeURL
    //       );
    //       loginWindow.postMessage({ action: "submitLogin" }, protegeURL);
    //     }
    //   }, 2000); // 适当的等待时间，根据实际情况调整
    // },

    //获取所有场景列表
    getScene() {
      getSceneList().then((response) => {
        console.log(response)
        this.scenetable = response.data.map((item) => {
          return {
            value: "选项"+item.sceneId, //设置value的值
            label: item.name, //设置label的值
          };
        });
      });
    },

    //根据给定的场景ID来获取杀伤链列表
    getSslListBySceneID(selectedValue) {
      this.showImageFlag = true;
      this.selectedScene = selectedValue;
      this.downloadImage()
      const scene_id = parseInt(selectedValue.match(/\d+/)[0]);
      getSslListBySceneID(scene_id).then((response) => {
        // console.log(response)
        this.sslTrueList = response.data.map((item) => item.sslId);
        this.sslList = response.data.map((item) => item.sslId);
        // console.log("getSslListBySceneID" + this.sslList);
        this.getssl();
        getLine(scene_id).then((response) => {
          this.parentData = response.data;
          // console.log(this.parentData);
          this.selectSsl(0);
          // this.$refs.index2.sendSslId(this.parentData, 0);
          this.$refs.index.sendActivityData(this.fromActivityData, 0);
          this.currentSsl=undefined
        });
      });
      //更改this.tableData
      getSceneInfoBySceneID(scene_id).then((response) => {
        // console.log("---------------");
        // console.log(response.data);
        // console.log("+++++++++");
        // console.log(response.data.description);
        this.tableData.forEach((item) => {
          if (item.name == "基本情况") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.description;
          }
          if (item.name == "场景名称") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.name;
          }
          if (item.name == "场景位置") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.location;
          }
          if (item.name == "作战任务") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.task;
          }
          if (item.name == "场景时间") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.startTime + "-" + response.data.endTime;
          }
          /*
          if (item.name == "我方装备") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.friendEquipment;
          }
          if (item.name == "敌方装备") {
            // 如果item.name存在于formData中，则进行复制
            item.value = response.data.enemyEquipment;
          }
          */
        });
      });
      getActivity(scene_id).then((response) => {
        // console.log("输入参数");
        // console.log(response.data);
        this.fromActivityData = response.data;
        this.$refs.index.sendActivityData(this.fromActivityData, 0);
        this.currentSsl=undefined;
      });
    },

    getssl() {
      if (this.selectedScene == null) {
        return;
      }
      const scene_id = parseInt(this.selectedScene.match(/\d+/)[0]);
      // console.log("sceneId");
      // console.log(scene_id);
      getList(scene_id)
        .then((response) => {
          // console.log("*****");
          // console.log(response);
          let temp = [];
          response.data.forEach((item) => {
            let flag = false;
            this.sslTrueList.forEach((item2) => {
              if (item.id == item2) flag = true;
            });
            if (flag) temp.push(item);
          });
          response.data = temp;
          // response.data = response.data.filter(item => this.ssltruelist.includes(item.id));
          // //
          // Assuming the response contains an array of SSL data
          this.sslList = response.data.map((item) => {
            // 使用replace方法去掉字符串两侧的方括号
            const modifiedItem = {
              ...item,
              spyEquipment: item.spyEquipment.replace(/^\[|\]$/g, ""),
              identificationEquipment: item.identificationEquipment.replace(
                /^\[|\]$/g,
                ""
              ),
              // decisionEquipment: item.decisionEquipment.replace(/^\[|\]$/g, ""),
              strikeEquipment: item.strikeEquipment.replace(/^\[|\]$/g, ""),
            };
            return modifiedItem;
          });
          this.addIdToRows();
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    },
    selectSsl(id) {
      this.$refs.index2.sendSslId(this.parentData, id);
      console.log("selectSsl");
      console.log(this.parentData);

      if (id != 0) {
        if (this.tableRow != null) {
          // console.log("tableRow1");
          // console.log(this.tableRow);
          this.tableRow.setAttribute("style", "background-color: #fff");
        }
        // console.log("tableRow2");
        // console.log()
        // this.tableRow =
        this.tableRow = document.getElementById("row-" + id);
        //console.log(this.tableRow);

        this.tableRow.setAttribute(
          "style",
          "background-color: rgb(228, 228, 205)"
        );
      }else{
          if (this.tableRow != null) {
          // console.log("tableRow1");
          // console.log(this.tableRow);
          this.tableRow.setAttribute("style", "background-color: #fff");
      }
      }

      this.$refs.index.sendActivityData(this.fromActivityData, id);
      if(id!=0)
        this.currentSsl=id
      else
        this.currentSsl=undefined
    },
    sendMessageToChild(message) {
      // 这个方法会作为事件处理函数，用于接收子组件传递的数据
      // console.log("Message received in parent:", message);
    },
    getChainInfo() {
      const idList = this.multipleSelection.map((item) => item.id);
      console.log(idList);
      getChainInfo(idList)
        .then((response) => {
          // 处理后端的响应
          console.log(response);

          // 更新表格数据
          this.sslList = response.data.map((item) => {
            return {
              id: item.id,
              // 其他字段根据需要添加
            };
          });

          // Rest of your code
          this.timeChainOption.xAxis.data = this.sslList.map(
            (item) => "杀伤链-" + item.id
          );
          this.precisionChainOption.xAxis.data = this.sslList.map(
            (item) => "杀伤链-" + item.id
          );
          this.accuracyChainOption.xAxis.data = this.sslList.map(
            (item) => "杀伤链-" + item.id
          );
          // 其他更新逻辑
          this.drawLine();
        })
        .catch((error) => {
          // 处理请求错误
          console.error(error);
        });
    },
    viewSceneAssessment() {
      // 处理查看场景评估结果按钮点击事件
      console.log("查看场景评估结果");
      console.log(this.selectedScene);
      // console.log(this.scenetable);
      // 在这里添加处理查看场景评估结果的逻辑
      // 使用编程式导航跳转到 analyse/index.vue
      //this.$router.push({ name: "AnalyseIndex" });
      this.$router.push({
        path: "/form/analyse",
        query: {
          selectedScene: this.selectedScene,
        },
      });
      // this.$router.push({ path: "/analyse/show" });
    },
    showForm() {
      // 打开对话框
      this.formDialogVisible = true;
    },
    closeFormDialog() {
      // 关闭对话框
      this.formDialogVisible = false;
      this.formData = {
        eventName: "",
        eventLocation: "",
        militaryTask: "",
        startTime: "",
        endTime: "",
        AWACS:{},
        formationList:[],
        target: {
          x: 0,
          y: 0,
          z: 0,
          a: 0,
        },
        description: "",
        ruleList: [],
        precisionChecked:false,
        precision:0.0,
        accuracyChecked:false,
        accuracy:0.0,
      };
      this.ruleList = [{ name: "", value: "", checked: false }];
      this.RuleequipmentList = [];
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    saveForm() {
      // 处理表单保存逻辑
      this.loading=true
      this.uploadSceneName=this.formData.eventName
      if(!this.formData.precisionChecked){
        this.formData.precision=0
      }
      if(!this.formData.accuracyChecked){
        this.formData.accuracy=0
      }
      if(!this.check021(this.formData.accuracy) || !this.check021(this.formData.precision)){
        this.$message({
          message:"精度值和准确度值只能为0到1的数值",
          type:"error"
        })
        return
      }
      console.log("保存表单", this.formData);
      // this.upload()
      // 在这里添加保存表单的其他逻辑
      creatSslscene(this.formData).then((response) => {
        console.log(response);
        this.imageUrl=''
        
        if (response.code == "0") {
          this.getScene();
          this.$message({
            showClose: true,
            message: '场景创建成功',
            type:'success'
          });
          this.loading=false
          
        } else {
          this.$message({
            showClose: true,
            message: '场景创建失败',
            type:'error'
          });
          this.loading=false
        }
        
        this.upload()
        this.localImageUrl = ''; // 设置 localImageUrl 为空字符串
        this.imageUrlFlag=false

        
        location.reload();
      })
      .catch((err) =>{
        this.loading=false
      });
      // 关闭对话框
        // this.formDialogVisible = false;
        // location.reload();
      this.closeFormDialog()
      console.log("清空之后的usn",this.uploadSceneName);
      // await this.sleep(2000); // 等待 2000 毫秒（2秒）
      

      
    },
    viewSceneBasicInfo() {
      // 处理查看场景基本情况按钮点击事件
      console.log("查看场景基本情况");
      // 在这里添加处理查看场景基本情况的逻辑
      // 打开场景基本情况对话框
      this.basicInfoDialogVisible = true;
      console.log(this.basicInfoDialogVisible);
    },

    closeBasicInfoDialog() {
      // 关闭场景基本情况对话框
      this.basicInfoDialogVisible = false;
    },
    highlightNumbers() {
      const descriptionElement = this.$refs.sceneDescription;
      const textContent = descriptionElement.textContent;

      // 使用正则表达式匹配数字
      const highlightedText = textContent.replace(
        /\d+/g,
        '<span class="highlighted-number">$&</span>'
      );

      // 将替换后的内容设置回原始元素
      descriptionElement.innerHTML = highlightedText;
    },
    drawWeaponLevels() {
      const svgContainer = d3
        .select(".description")
        .select(".weapon-svg")
        .attr("width", 200) // 设置SVG容器的宽度
        .attr("height", 300); // 设置SVG容器的高度

      const weaponData = [
        { level: "第一层级", planes: ["plane1", "plane2"], color: "blue" },
        { level: "第二层级", planes: ["plane3", "plane4"], color: "green" },
        { level: "第三层级", planes: ["plane5", "plane6"], color: "orange" },
      ];

      // 绘制平行四边形和飞机
      const weaponGroups = svgContainer
        .selectAll(".weapon-group")
        .data(weaponData)
        .enter()
        .append("g")
        .attr("class", "weapon-group")
        .attr("transform", (d, i) => `translate(20, ${i * 160})`);

      weaponGroups
        .append("polygon")
        .attr("points", "0,0 80,0 60,150 20,150")
        .style("fill", (d) => d.color);

      weaponGroups
        .selectAll(".plane")
        .data((d) => d.planes)
        .enter()
        .append("image")
        .attr("xlink:href", "../../../assets/Jjj.jpg") // 实际的飞机图标路径
        .attr("width", 30)
        .attr("height", 30)
        .attr("x", (d, i) => i * 35)
        .attr("y", 80);

      // 绘制连线
      const lineData = [
        { source: [80, 75], target: [250, 75], color: "blue" },
        { source: [80, 235], target: [250, 235], color: "green" },
      ];

      svgContainer
        .selectAll(".line")
        .data(lineData)
        .enter()
        .append("line")
        .attr("x1", (d) => d.source[0])
        .attr("y1", (d) => d.source[1])
        .attr("x2", (d) => d.target[0])
        .attr("y2", (d) => d.target[1])
        .attr("stroke", (d) => d.color)
        .attr("stroke-width", 2);

      // 绘制红点目标
      svgContainer
        .append("circle")
        .attr("cx", 280)
        .attr("cy", 75)
        .attr("r", 5)
        .style("fill", "red");
    },
    //更新
    // 显示装备对话框
    showEquipmentDialog() {
      // this.selectedEquipment.level = level;
      this.equipmentDialogVisible = true;
      this.equipmentList.forEach((equipment) => {
        equipment.x=0
        equipment.y=0
        equipment.z=0
        equipment.weapon=0
      });
    },

    closeEquipmentDialog() {
      // 关闭对话框
      this.equipmentDialogVisible = false;
      this.equipmentList.forEach((equipment) => {
        equipment.x=0
        equipment.y=0
        equipment.z=0
        equipment.weapon=0
      });
      this.AWACS={
        name:"",
        x:0,
        y:0,
        z:0
      }
    },
    // 确认装备选择
    confirmEquipmentSelection() {
      // 获取选定的装备列表
      // const selectedList = this.equipmentList.filter(
      //   (equipment) => equipment.quantity > 0
      // );
      if(!this.check021(this.AWACS.accuracy)){
        this.$message({
          message:"准确度值只能为0到1的数值",
          type:"error"
        })
        return
      }
      if(this.checkedChooseAWACS){
        this.formData.AWACS=this.deepClone(this.AWACS,{})
      }else{
        this.formData.AWACS=null
      }

      console.log("新建场景信息：")
      console.log(this.formData)
      this.equipmentDialogVisible = false;
    },

    // 显示装备对话框并设置选定的级别
    showRuleDialog() {
      this.RuleDialogVisible = true;
    },

    closeRuleDialog() {
      // 关闭对话框
      this.deviationDialogVisible = false;
      this.ruleList=[{name:"",value:0,checked:false}]
    },

    confirmRuleSelection() {
      let flag=true
      // this.ruleList.forEach(rule=>{
      //   if(!this.check021(rule.value)){
      //     this.$message({
      //       message:"误差值只能为0到1的数值",
      //       type:"error"
      //     })
      //     flag=false
      //     return
      //   }
      // })
      if(!flag){
        return
      }
      // 获取选定的规则
      const selectedList = this.ruleList.filter((rule) => rule.checked);
      console.log("误差信息");
      console.log(selectedList);
      this.deviaEquipment.deviationList=selectedList.map(({ name, value }) => ({
        name,
        value,
      }));
      // 根据选定的级别更新ourEquipment中的对应字段
      // this.formData.ruleList = selectedList.map(({ name, value }) => ({
      //   name,
      //   value,
      // }));

      // console.log("gghggggg");
      // console.log(this.formData.ruleList);
      // 关闭对话框
      this.closeRuleDialog()
      // this.deviationDialogVisible = false;
    },
  },
  created() {
    // 设置按钮的可见性
    // 显示时间对比按钮，将 timeCompareVisible 设置为 true
    this.timeCompareVisible = true;
    this.accuracyCompareVisible = true;
    this.precisionCompareVisible = true;
    // 在一定时间后修改 showPlanes，触发过渡效果
    setTimeout(() => {
      this.showPlanes = false;
    }, 2000); // 2秒后修改 showPlanes
  },
};
</script>

<style scoped>
/* 自定义样式 */
.description {
  margin: 0;
  position: relative;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .center{
    margin-left:auto;
    margin-right:auto;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.position-input {
   width: 60px;
   /* margin-left:10px; */
   margin-right:10px;
}

.comparison {
  position: relative;
}

/* 飞机样式 */
.plane {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  /* 初始位置 */
  left: 0;
  top: 50%;
  transform: translate(0, -50%);
  /* 过渡效果 */
  transition: left 2s ease-in-out;
}

/* 过渡效果的定义 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.highlighted-number {
  color: red;
}
/* 使用 SVG 绘制的平行四边形样式 */
.weapon-group polygon {
  fill: #fff; /* 设置平行四边形的背景颜色 */
  transform: skew(-20deg); /* 使用 skew 变换创建平行四边形效果 */
  margin: 10px; /* 设置平行四边形之间的间距 */
}

/* 每个平行四边形的具体位置可以通过 top、left、right、bottom 等属性调整 */
.weapon-group:nth-child(1) polygon {
  top: 20px;
  left: 30px;
}

.weapon-group:nth-child(2) polygon {
  top: 120px;
  left: 150px;
}

.weapon-group:nth-child(3) polygon {
  top: 250px;
  left: 280px;
}
.button-container {
  margin-top: 10px;
}
.el-button {
  margin-right:10px;
}
.custom-button {
  background-color: #409eff; /* 设置背景颜色 */
  color: #ffffff; /* 设置文本颜色 */
  border: none; /* 移除按钮边框 */
  border-radius: 5px; /* 应用边框半径以实现圆角 */
  padding: 10px 15px; /* 调整填充以获得更好的间距 */
  cursor: pointer; /* 在悬停时更改光标 */
}

.custom-button1 {
  background-color: #ffa500; /* 设置背景颜色 */
  color: #ffffff; /* 设置文本颜色 */
  border: none; /* 移除按钮边框 */
  border-radius: 5px; /* 应用边框半径以实现圆角 */
  padding: 10px 15px; /* 调整填充以获得更好的间距 */
  cursor: pointer; /* 在悬停时更改光标 */
}

.custom-button:hover {
  background-color: #66b1ff; /* 悬停时更改背景颜色 */
}

.equipment-row {
  border-bottom: 1px solid #ebeef5; /* 行之间添加底部边框 */
  padding: 10px 0; /* 行内边距 */
}

.equipment-checkbox {
  margin-top: 5px;
}

.equipment-name {
  line-height: 32px;
  font-weight: bold;
}

.equipment-quantity {
  width: 80%;
}

.equipment-row {
  border-bottom: 1px solid #ebeef5;
  padding: 10px 0;
}

.equipment-checkbox {
  margin-top: 5px;
}

.equipment-name {
  line-height: 32px;
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
}

.equipment-quantity {
  width: 100%;
}

/* 样式可以根据自己的需要进行调整 */
.highlightable {
  padding: 10px;
  border: 1px solid #ccc;
  cursor: pointer;
}

.is-active {
  background-color: rgb(228, 228, 205);
  /* 其他高亮样式 */
}

.bc {
   /* background-color: white; */
   border: 1px solid rgb(228 229 231);
}
.nowrap{
  display: inline-block;
  /* overflow: hidden; */
  white-space: nowrap;
}

#imageDisplay{
  max-width: 100%; /* 让图片的最大宽度为父容器宽度 */
  height: auto;   /* 保持图片的宽高比例 */
  display: block; /* 去掉图片默认的下外边距，以避免产生空隙 */
  margin: auto;    /* 居中显示图片 */
}

#imageDialog{
  max-width: none !important; /* 取消 el-dialog 默认的最大宽度限制 */
  width: auto !important;     /* 让 el-dialog 宽度自动适应内容 */
}
</style>
